package com.lagou.edu.intercept;

import com.lagou.edu.util.CookieUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 此拦截器用于拦截用户的登录权限
 */
public class AccessIntercept extends HandlerInterceptorAdapter {

    private static final String LOGIN_COOKIE = "login_cook";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        if("/demo/login".equals(uri) || "/demo/signup".equals(uri)){
            return true;
        }
        String value = CookieUtil.getCookieValueByName(request, LOGIN_COOKIE);
        if(!"1".equals(value)){
            response.sendRedirect("/demo/login?error=auth error");
            return false;
        }
        return super.preHandle(request, response, handler);
    }
}
